package com.scalar.chiptrack.operations.reports.actionCommands;

import com.scalar.chiptrack.actioncommands.ActionCommand;
import com.scalar.chiptrack.operations.reports.dao.DataDumpReportsDAO;
import com.scalar.chiptrack.operations.reports.DataDumpReportsHelper;
import com.scalar.chiptrack.utils.ConfigManager;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForm;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.File;
import java.util.HashMap;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * User: muralikrishna.yengal
 * Date: Dec 9, 2005
 * Time: 2:45:18 PM
 * To change this template use File | Settings | File Templates.
 */
public class AssemblyTransactionDataDumpReportActionCommand extends ActionCommand {
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
    {
        Workbook workbook;
        FileOutputStream fileOut;
        String filePath;
        HashMap errors = ( HashMap )request.getAttribute ( ERROR_MESSAGES );
        String fromDate = request.getParameter("from");
        String toDate = request.getParameter("to");
        try
        {
            ArrayList lotInfoList = DataDumpReportsDAO.getAssemblyTransactionDataDumpReport( null, fromDate, toDate );
            workbook =  DataDumpReportsHelper.getWorkbook( lotInfoList, "Assembly Trans Dump Report", fromDate,toDate, null );

            filePath = request.getSession().getServletContext().getRealPath( ConfigManager.getDataDumpReportsFilePath() );
            boolean exists = ( new File( filePath ) ).exists();
            if ( !exists )
            {
                File file = new File( filePath );
                file.mkdirs();
            }
            String fileName = "AssemblyTransactionDataDumpReport.xls";
            fileOut = new FileOutputStream( filePath + "/" + fileName );
            if ( workbook != null )
            {
                try
                {
                    workbook.write( fileOut );
                    request.setAttribute ( "fileName", fileName );
                }
                catch ( Exception e )
                {
                    errors.put ( "Could not write excel file to disk", null );
                    e.printStackTrace();
                }
            }
            fileOut.close();
        }
        catch ( Exception e)
        {
            errors.put ( "Could not generate excel file", null );
            e.printStackTrace();
        }
        return mapping.findForward( "success" );
    }
}
